package com.cml.dm.engine.intercept;

import com.cml.dm.admin.util.ResponseData;
import com.cml.dm.engine.detector.BRStatusDetector;
import com.cml.dm.engine.exception.DMException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Component
@Aspect
public class DMRejectIntercept {
    @Autowired
    private BRStatusDetector brStatusDetector;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.DeleteMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.GetMapping)")
    private void pointCut(){}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        boolean ok = this.containOrgId(proceedingJoinPoint);
        if(ok){
            throw new RuntimeException("此组织正在进行数据备份/恢复，请稍后");
        }
        try {
            return proceedingJoinPoint.proceed();
        }catch (DMException e){
            return ResponseData.error(e.getMessage());
        }
    }

    private boolean containOrgId(JoinPoint joinPoint){
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        String[] argsNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        Object[] argsValue = joinPoint.getArgs();
        StringBuffer argsStr = new StringBuffer();
        int index = 0;

        for(String argName : argsNames){
            if(argName.equals("orgId")){
                String value = argsValue[index].toString();
                return brStatusDetector.processing(value);
            }
            index++;
        }
        return false;
    }

}
